import dayjs from 'dayjs';
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter';

dayjs.extend(isSameOrAfter);

/**
 * 日期时间格式化
 * @param fmt
 * @param date
 */
export function dateFormat(date: Date, format?: string): string {
    const year = `${date.getFullYear()}`;
    let month = `${date.getMonth() + 1}`;
    if (month.length === 1) {
        month = `0${month}`;
    }
    let day = `${date.getDate()}`;
    if (day.length === 1) {
        day = `0${day}`;
    }

    let hours = `${date.getHours()}`;
    if (hours.length === 1) {
        hours = `0${hours}`;
    }
    let minutes = `${date.getMinutes()}`;
    if (minutes.length === 1) {
        minutes = `0${minutes}`;
    }
    let seconds = `${date.getSeconds()}`;
    if (seconds.length === 1) {
        seconds = `0${seconds}`;
    }

    return (format || 'yyyy-MM-dd hh:mm:ss')
        .replace(/yyyy/g, year)
        .replace(/MM/g, month)
        .replace(/dd/g, day)

        .replace(/hh/g, hours)
        .replace(/mm/g, minutes)
        .replace(/ss/g, seconds);
}

export function isAfterSame(currentDay: string, otherDay: Date): boolean {
    if (!currentDay && !otherDay) {
        throw new Error('[date error]');
    }
    return dayjs(otherDay).isSameOrAfter(currentDay);
}

/**
 * 对象赋值
 * @param {Object} targetObj
 * @param {Object} sourceObj
 * @param {String Array}keys
 */
export function objectAssignment(targetObj: object, sourceObj: object, keys?: string[]) {
    keys = keys || Object.keys(targetObj);
    keys.forEach((key) => {
        if (Object.prototype.hasOwnProperty.call(sourceObj, key)) {
            targetObj[key] = typeof sourceObj[key] === 'object' ? JSON.parse(JSON.stringify(sourceObj[key])) : sourceObj[key];
        }
    });
}